package com.example.cmh.service.impl;

import com.example.cmh.mapper.DepartmentMapper;
import com.example.cmh.pojo.Department;
import com.example.cmh.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门服务实现类
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {
    
    @Autowired
    private DepartmentMapper departmentMapper;
    
    @Override
    public Map<String, Object> getDepartments(String departmentName, String departmentStatus) {
        // 计算偏移量

        // 获取部门列表
        List<Department> departments = departmentMapper.getDepartments(departmentName, departmentStatus);
        
        // 获取总数
        Integer total = departmentMapper.getDepartmentsCount(departmentName, departmentStatus);
        
        // 构建分页结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", departments);
        result.put("total", total);

        return result;
    }
    
    @Override
    public Department getDepartmentsById(Integer departmentId) {
        return departmentMapper.getDepartmentsById(departmentId);
    }
    
    @Override
    public void addDepartments(Department department) {
        // 设置默认值
        if (department.getDeptLevel() == null) {
            department.setDeptLevel(0);
        }
        if (department.getDepartmentStatus() == null) {
            department.setDepartmentStatus(0);
        }
        if (department.getRegisterTime() == null) {
            department.setRegisterTime(new Date());
        }
        
        // 如果设置了上级部门，则level设置为上级部门的level+1
        if (department.getSuperiorId() != null) {
            Department superiorDepartment = departmentMapper.getDepartmentsById(department.getSuperiorId());
            if (superiorDepartment != null) {
                department.setDeptLevel(superiorDepartment.getDeptLevel() + 1);
            }
        }
        
        departmentMapper.addDepartments(department);
    }
    
    @Override
    public void updateDepartment(Department department) {
        departmentMapper.updateDepartment(department);
    }
    
    @Override
    public void deleteDepartment(Integer departmentId) {
        departmentMapper.deleteDepartment(departmentId);
    }
    
    @Override
    public void deleteDepartmentByName(String departmentName) {
        departmentMapper.deleteDepartmentByName(departmentName);
    }
    
    @Override
    public Department getDepartmentByName(String departmentName) {
        return departmentMapper.getDepartmentByName(departmentName);
    }
} 